<template>
  <div id="teamPage">
    <van-search
        v-model="searchText"
        placeholder="搜索队伍"
        clearable
        @search="onSearch"
    />

    <van-tabs v-model:active="activeTab" @change="onTabChange">
      <van-tab title="公开" name="public"/>
      <van-tab title="加密" name="private"/>
    </van-tabs>

    <div class="action-buttons">
      <van-button type="primary" @click="toAddTeam">创建队伍</van-button>
    </div>

    <van-loading v-if="loading" vertical>加载中...</van-loading>

    <team-card-list :teamList="teamList"/>

    <van-empty
        v-if="!loading && teamList.length === 0"
        :description="activeTab === 'public' ? '暂无公开队伍' : '暂无加密队伍'"
    />

  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import myAxios from '../plugins/myAxios';
import { showFailToast } from 'vant';
const activeTab = ref("public");
const router = useRouter();
const teamList = ref([]);
const searchText = ref('');
const loading = ref(false);

const toAddTeam = () => {
  router.push('/team/add');
};


const listTeam = async (val = '', status = 0) => {
  try {
    loading.value = true;
    const res = await myAxios.get('/team/list', {
      params: {
        searchText: val,
        pageNum: 1,
        status,
        pageSize: 10
      }
    });

    console.log('Response received:', res);
    if (res?.code === 0) {
      teamList.value = res.data?.records || res.data?.list || res.data || [];
    } else {
      showFailToast(res?.description || `傻眼了 还不赶紧登录 (code: ${res?.code})`);
    }
  } catch (error) {
    console.error('Request failed:', error);
    showFailToast(`网络错误: ${error.message}`);
  } finally {
    loading.value = false;
  }
};

const onTabChange = (name) => {
  const statusMap = {
    public: 0,
    private: 2
  };
  listTeam(searchText.value, statusMap[name]);
};

const onSearch = (val) => {
  listTeam(val);
};

onMounted(() => {
  listTeam();
});
</script>